package com.dubbo.consumer;

import com.alibaba.dubbo.config.spring.ReferenceBean;
import com.dubbo.provider.api.OpenApiDispatcher;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * \* User: MeiZhongHao
 * \* Date: 2019-04-24
 * \* Time: 14:51
 * \* Description:
 * \
 */
@Service
public class OpenApiDispatcherServiceImpl implements OpenApiDispatcherService, ApplicationContextAware {

    private final ConcurrentMap<String, ReferenceBean<OpenApiDispatcher>> referenceConfigs = new ConcurrentHashMap<>();

    private ApplicationContext applicationContext;

    @Override
    public OpenApiDispatcher getOpenApiDispatcher(String group) {
        String openApiDispatcherBeanName = getOpenApiDispatcherBeanName(group);
        ReferenceBean<OpenApiDispatcher> referenceBean = referenceConfigs
                .get(openApiDispatcherBeanName);
        if (referenceBean == null) {
            referenceBean = new ReferenceBean<OpenApiDispatcher>();
            referenceBean.setId(openApiDispatcherBeanName);
            referenceBean.setInterface(OpenApiDispatcher.class.getName());
            referenceBean.setCheck(false);
            referenceBean.setTimeout(60000);
            referenceBean.setGroup(group);
            referenceBean.setApplicationContext(applicationContext);
            try {
                referenceBean.afterPropertiesSet();
                referenceConfigs.putIfAbsent(openApiDispatcherBeanName, referenceBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return referenceBean.get();
    }

    private String getOpenApiDispatcherBeanName(String group) {
        return StringUtils.isEmpty(group) ? "openApiDispatcher" : group + "OpenApiDispatcher";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}